//
//  MainViewController.m
//  Rabbit
//
//  Created by 阿帕 on 2018/11/3.
//  Copyright © 2018年 GCY. All rights reserved.
//

#import "MainViewController.h"

//customView
#import "MainFirstBannerView.h"
#import "MainActivityView.h"
//#import "PrivacyAgreeView.h"

//controllers
#import "LoginViewController.h"
#import "CYWebViewViewController.h"

#import "YunDanCenterViewController.h"
#import "HuoYuanDetailViewController.h"
#import "HuoYuanDetailLatestVC.h"
#import "YunDanCenterTabbar.h"

#import "PaiDanViewController.h"
#import "AccountInformationViewController.h"
#import "NoticeMessageViewController.h"
#import "FreightIndexViewController.h"
#import "FreightStatisticsViewController.h"
#import "OilDropManageViewController.h"
#import "WJYWKViewController.h"
#import "GasStationTabBarVC.h"
#import "HomeXieYView.h"
#import "AuthorizationController.h"
#import "UpIDCodeController.h"
#import "IDentityCodeController.h"
#import "IDCardAuthenticationController.h"

@interface MainViewController()<MainFirstBannerDelegate, MainActivityDelegate>

@property(strong, nonatomic)UIScrollView *scrollView;

@property(strong, nonatomic)UIImageView *bottomImageView;

@property(strong, nonatomic)MainFirstBannerView *firstBannerView;

@property(strong, nonatomic)MainActivityView *activityView;

@property(strong, nonatomic)HomeXieYView *xieyiView;

@property(strong, nonatomic)NSMutableArray *firstBannerImages;
@property(strong, nonatomic)NSMutableArray *liveArray;
@property(strong, nonatomic)NSMutableArray *bannerArray;
@property(strong, nonatomic)NSMutableArray *activityArray;

@end

@implementation MainViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!TOKEN_ISEMPTY) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            for (int i = 1; i<=3; i++) {
                [UIView animateWithDuration:0.5f animations:^{
                    UIView *view = [self.tabBarController.view viewWithTag:CJAlertDueTag+i];
                    view.alpha = 1;
                } completion:nil];
            }
        });
    }
    [self networkingInfoIsFace];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    for (int i = 1; i<=3; i++) {
        UIView *view = [self.tabBarController.view viewWithTag:CJAlertDueTag+i];
        view.alpha = 0;
    }
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [KNotificationCenter addObserver:self selector:@selector(refreshHomePageData:) name:LOGIN_SUCCESS object:nil];
    [KNotificationCenter addObserver:self selector:@selector(clearData) name:LOGIN_LOGOUT object:nil];
    [KNotificationCenter addObserver:self selector:@selector(requestNoticeUnreadTotal) name:REFRESHHOMENOTICECOUNT object:nil];
    [KNotificationCenter addObserver:self selector:@selector(popToHomePushJieDan) name:@"popToHomePushJieDan" object:nil];
    [KNotificationCenter addObserver:self selector:@selector(popToHomePushDaiYunShu) name:@"popToHomePushDaiYunShu" object:nil];
    self.navigationItem.title = APP_NAME;
    
    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [resetButton setTitle:@"客服" forState:UIControlStateNormal];
    resetButton.titleLabel.font = font(14);
    [resetButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(rightBarItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:resetButton];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;
    
    [self setupBaseView];
    
    //轮播视图
    [self setupFirstBannerView];
    
    //最新货源
    [self setupActivityView];
    
    [self homeDataRequest];
    
    //    [[PrivacyAgreeView shared] show];
    [self networkingDYT];
    
}

- (void)rightBarItemClick {

    CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
    webVC.titleString = @"客服";
    webVC.kefu = @"1";
    webVC.urlString = @"https://huanxin.deskpro.cn/webim/im.html?configId=b04d6591-d151-4825-a74e-6d584feeef09&restServer=hxim.deskpro.cn&xmppServer=scim.deskpro.cn";
    webVC.state = 1;
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)popToHomePushJieDan{
    YunDanCenterTabbar *ydcVC = [[YunDanCenterTabbar alloc] init];
    [self.navigationController pushViewController:ydcVC animated:NO];
}
- (void)popToHomePushDaiYunShu{
    YunDanCenterTabbar *ydcVC = [[YunDanCenterTabbar alloc] init];
    [self.navigationController pushViewController:ydcVC animated:NO];
}
- (void)dealloc {
    [KNotificationCenter removeObserver:self name:LOGIN_SUCCESS object:nil];
    [KNotificationCenter removeObserver:self name:LOGIN_LOGOUT object:nil];
    [KNotificationCenter removeObserver:self name:REFRESHHOMENOTICECOUNT object:nil];
    [KNotificationCenter removeObserver:self name:@"popToHomePushJieDan" object:nil];
    [KNotificationCenter removeObserver:self name:@"popToHomePushDaiYunShu" object:nil];
}

//登录成功后回调
- (void)refreshHomePageData:(NSNotification *)notf {
    [self homeDataRequest];
    [self requestNoticeUnreadTotal];
    if (![CJStringWithFormat(@"%@", notf.object) isEqualToString:@"1"]) {
        self.xieyiView = [[HomeXieYView alloc] initWithFrame:CGRectMake(0, 0,ScreenW, ScreenH) Url: CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=1",BasicDomainURL)];
        [self.xieyiView.comitButton addTarget:self action:@selector(xiYiBtnClick) forControlEvents:UIControlEventTouchUpInside];
       [ [UIApplication sharedApplication].keyWindow addSubview:self.xieyiView];
    }
}
- (void)xiYiBtnClick{
    [self.xieyiView removeFromSuperview];
    [self networkingDYT];

}
//退出登录的回调
- (void)clearData {
    //    _scrollView.mj_header = nil;
    [self.activityArray removeAllObjects];
    self.firstBannerView.advertArray = @[];//未登录不能查看运价指数
    self.firstBannerView.unreadNoticeTotal = 0;//未登录置空消息数
    self.activityView.activityArray = self.activityArray;
    self.scrollView.contentSize = CGSizeMake(ScreenW, ScreenH - TabBarHeight - NavHeight);
}

- (void)setupBaseView {
    
    self.scrollView.backgroundColor = RGB(249, 249, 249);

}

- (void)setupFirstBannerView {
    
    _firstBannerView = [[MainFirstBannerView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 325)];
    _firstBannerView.delegate = self;
    [_scrollView addSubview:_firstBannerView];
}

- (void)setupActivityView {
    
    _activityView = [[MainActivityView alloc] initWithFrame:CGRectMake(0, _firstBannerView.cy_bottom + 10, ScreenW, 0)];
    _activityView.delegate = self;
    [_scrollView addSubview:_activityView];
    
}
- (void)networkingDYT{
    NSString * codeStr = [UserDefaultUtil valueForKey:userDriverCode];
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/%@",[NSString stringWithFormat:@"%@/ntocc-basic-api/dyt/getDriverExtInfo",[ReAddressDynamic shared].baseUrl],codeStr) withParameter:@{} withVC:self netName:@"" success:^(id response, NSString *msg) {
        if ([response[@"isSignDyt"] intValue] == 0) {
//            AuthorizationController *vc = [[AuthorizationController alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@",[NSString stringWithFormat:@"%@/ntocc-basic-api/orderDetailContract/determineWhetherDriverNeedCreateContractKQD",[ReAddressDynamic shared].baseUrl]) withParameter:@{} withVC:self netName:@"撮合协议签" success:^(id response, NSString *msg) {
        NSLog(@"%@",response);
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}
#pragma mark - 首页请求
- (void)homeDataRequest {
    
    WEAKSELF
    dispatch_group_t group = dispatch_group_create();
    //轮播
    NSDictionary *dicParams = @{
        @"branchCode": [UserDefaultUtil valueForKey:BranchCode] == nil ? Default_BranchCode : [UserDefaultUtil valueForKey:BranchCode],
        @"type": @"driver",
        @"status": @0,
        @"pageNum": @1,
        @"pageSize": @10,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    dispatch_group_enter(group);
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],HOME_BANNER) withParameter:dicParams withVC:self netName:@"首页轮播图" success:^(id response, NSString *msg) {
        
        dispatch_group_leave(group);
        
        self.bannerArray = [MainBannerModel mj_objectArrayWithKeyValuesArray:response[@"records"]];;
        
        for (MainBannerModel *model in self.bannerArray) {
            [self.firstBannerImages addObject:model.img];
        }
        
        weakSelf.firstBannerView.imageGroupArray = self.firstBannerImages;
        
    } failure:^(NSInteger code, NSString *msg) {
        [weakSelf.scrollView.mj_header endRefreshing];
    }];
    
    
    //运价指数
    dispatch_group_enter(group);
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER_ORDERFREIGHTINDEXLIST) withParameter:dicParams withVC:self netName:@"运价指数列表" success:^(id response, NSString *msg) {
        
        dispatch_group_leave(group);
        
        weakSelf.liveArray = [FreightIndexModel mj_objectArrayWithKeyValuesArray:response[@"records"]];;
        
        _firstBannerView.advertArray = weakSelf.liveArray;
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    
    
    if (TOKEN_ISEMPTY) {
        [weakSelf.scrollView.mj_header endRefreshing];
    } else {
        
        //货源列表
        dispatch_group_enter(group);
        NSDictionary *huoyuanParams = @{
            @"pageNum": @1,
            @"pageSize": @5,
            @"isFromOrderHall": @"1",//访问货源大厅必传1
            @"sortField": @"gmt_created",//排序字段
            @"sortType": @"desc",//排序方式
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tms-api",[ReAddressDynamic shared].baseUrl], ORDER_ORDERHALLLIST) withParameter:huoyuanParams withVC:self netName:@"首页货源列表" success:^(id response, NSString *msg) {
            
            [weakSelf.scrollView.mj_header endRefreshing];
            
            dispatch_group_leave(group);
            
            self.activityArray = [MainActivityModel mj_objectArrayWithKeyValuesArray:response[@"records"]];;
            
            weakSelf.activityView.activityArray = self.activityArray;
            weakSelf.activityView.frame = CGRectMake(0, weakSelf.firstBannerView.cy_bottom + 10, ScreenW, 40 + 210 * self.activityArray.count);
            weakSelf.scrollView.contentSize = CGSizeMake(ScreenW, weakSelf.activityView.cy_bottom);
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
    }
    
    /*组织机构*/
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PARTYGROUP_GETDEFAULT) withParameter:nil withVC:self netName:@"获取默认机构信息" success:^(id response, NSString *msg) {
        
        if ([DCSpeedy isBlankDictionary:response] == NO) {
            
            [UserDefaultUtil saveValue:response[@"code"] forKey:BranchCode];
            [UserDefaultUtil saveValue:response[@"telephone"] forKey:CustomerTel];//客服电话
            [UserDefaultUtil saveValue:response[@"complainLine"] forKey:CustomerLine];//集团客服电话
            [UserDefaultUtil saveValue:response[@"salt"] forKey:Branch_Salt];//机构盐值（忘记密码的上传图片使用）
            [UserDefaultUtil saveValue:response[@"isLoginNeedSMS"] forKey:IsLoginNeedSMS];
            
        } else {
            [UserDefaultUtil saveValue:Default_BranchCode forKey:BranchCode];
        }
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
    
    if (TOKEN_ISEMPTY) {
        
    } else {
        [self requestNoticeUnreadTotal];
    }
}

///  未读通知消息数量
- (void)requestNoticeUnreadTotal {
    WEAKSELF
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], JPUSHMESSAGE, UNREADTOTAL) withParameter:nil withVC:self netName:@"未读消息数量" success:^(id response, NSString *msg) {
        DebugLog(@"=========未读消息数量=========== %@", response);
        weakSelf.firstBannerView.unreadNoticeTotal = [response integerValue];
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#pragma mark - 刷新数据
- (void)loadNewData {
    
    [self.firstBannerImages removeAllObjects];
    [self.bannerArray removeAllObjects];
    [self.activityArray removeAllObjects];
    
    [self homeDataRequest];
}

#pragma mark - MainFirstBannerDelegate
- (void)firstBannerIndexClick:(NSInteger)index {
    DebugLog(@"点击了%zd轮播图",index);
    
    MainBannerModel *model = [self.bannerArray objectAtIndex:index];
    
    if ([DCSpeedy isBlankString:model.url] == NO) {
        CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
        webVC.titleString = model.title;
        webVC.urlString = model.url;
        webVC.state = 1;
        [self.navigationController pushViewController:webVC animated:YES];
    }
    
}
- (void)buttonIndexClick:(NSInteger)index {
    
    if ([DCSpeedy judgeUserIsLogin] == NO) return;
    
    if (index == 0) {
        //运单中心
        YunDanCenterTabbar *ydcVC = [[YunDanCenterTabbar alloc] init];
        [self.navigationController pushViewController:ydcVC animated:YES];
        
    } else if(index == 1) {
        //            if ([[UserDefaultUtil valueForKey:HOME_OILPAYTYPE] integerValue] == 0 || [UserDefaultUtil valueForKey:HOME_OILPAYTYPE] == nil) {
        //                //账户中心
        //                AccountInformationViewController *aivc = [[AccountInformationViewController alloc] init];
        //                [self.navigationController pushViewController:aivc animated:YES];
        //
        //            } else {
        //
        //            }
        
        //在线汽油
        //            [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], ZHAOYOU_H5) withParameter:nil withVC:self netName:@"在线油气" success:^(id response, NSString *msg) {
        //
        //                CYWebViewViewController *wvc = [[CYWebViewViewController alloc] init];
        //                wvc.state = 1;
        //                wvc.urlString = response[@"res"][@"reqestH5Address"];
        //                wvc.titleString = @"在线油气";
        //                [self.navigationController pushViewController:wvc animated:YES];
        //
        //            } failure:^(NSInteger code, NSString *msg) {
        //
        //            }];
        
        GasStationTabBarVC *tbVC = [GasStationTabBarVC new];
        [self.navigationController pushViewController:tbVC animated:YES];
        return;
        
        if ([[UserDefaultUtil valueForKey:Login_Branch][@"zhaoyouService"] isEqual:@"1"]) {
            //找油网服务
            NSDictionary *param = @{@"token":[UserDefaultUtil valueForKey:USER_TOKEN], @"username":[UserDefaultUtil valueForKey:USER_PHONE]};
            [HTTPManager getNetworkRequest:[[ReAddressDynamic shared].baseUrl stringByAppendingString:WANJINYOU_H5]
                             withParameter:param
                                    withVC:self
                                   netName:@"在线油气"
                                   success:^(id response, NSString *msg) {
                // 找油网
//                CYWebViewViewController *wvc = [[CYWebViewViewController alloc] init];
//                wvc.state = 1;
//                wvc.urlString = response[@"res"][@"reqestH5Address"];
//                wvc.titleString = @"在线油气";
//                [self.navigationController pushViewController:wvc animated:YES];
                
                // 万金油
                WJYWKViewController *wjyVC = WJYWKViewController.new;
                wjyVC.title = @"在线油气";
                wjyVC.urlStr = response[@"loginUrl"];
//                wjyVC.urlStr = @"http://t1vip.nucarf.cn/PublicApi/MemberCart/authMember?sign=cf6381c109706f38b5fe71a518298597_1634542757_90884&appid=4161451405142bcc1d8bfc0eeb84aa0a&username=18556923403";
                [self.navigationController pushViewController:wjyVC animated:YES];

            } failure:^(NSInteger code, NSString *msg) {

            }];
            
        } else {
            
            OilDropManageViewController *odmvc = [[OilDropManageViewController alloc] init];
            [self.navigationController pushViewController:odmvc animated:YES];
        }
        
    } else if(index == 2) {
        
        //运费统计
        FreightStatisticsViewController *fsvc = [[FreightStatisticsViewController alloc] init];
        [self.navigationController pushViewController:fsvc animated:YES];
        
    }else{
        //消息中心
        NoticeMessageViewController *nmvc = [[NoticeMessageViewController alloc] init];
        [self.navigationController pushViewController:nmvc animated:YES];
    }
    
}
-(void)networkingInfoIsFace{
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN],@"version":@(1)} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
        if ([response[@"isRealNameAuthentication"] intValue] == 0) {//须实名认证 1 已认证 0未认证
            if ([response[@"isOldParty"] intValue] == 0) {//是否是老用户 1老用户 0新用户
                IDCardAuthenticationController * vc = [[IDCardAuthenticationController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                IDentityCodeController *vc = [[IDentityCodeController alloc] init];
                vc.name = response[@"name"];
                vc.IDCod = response[@"idNo"];
                vc.idCardDueDate = response[@"idCardDueDate"];
                vc.isOldType = @"1";
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}
- (void)verticalMarqueeIndexClick:(NSInteger)index {
    
    if ([DCSpeedy judgeUserIsLogin] == NO) return;
    
    FreightIndexViewController *fivc = [[FreightIndexViewController alloc] init];
    [self.navigationController pushViewController:fivc animated:YES];
}

#pragma mark - 最新货源列表点击事件
- (void)activityIndexClick:(NSInteger)index {
    
    if (index == 2000) {
        //更多货源
        self.navigationController.tabBarController.selectedIndex = 1;
        
    } else {
        
        if ([DCSpeedy judgeUserIsLogin] == NO) return;
        
        //货源item
        MainActivityModel *model = [self.activityArray objectAtIndex:index];
        HuoYuanDetailViewController *hydVC = [[HuoYuanDetailViewController alloc] init];
        hydVC.orderCode = model.code;
        [self.navigationController pushViewController:hydVC animated:YES];
        
        //        HuoYuanDetailLatestVC *hydVC = [[HuoYuanDetailLatestVC alloc] init];
        //        hydVC.orderCode = model.code;
        //        [self.navigationController pushViewController:hydVC animated:YES];
    }
}

#pragma mark - lazyLoad
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - TabBarHeight - NavHeight)];
        _scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (UIImageView *)bottomImageView {
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] init];
        _bottomImageView.contentMode = UIViewContentModeScaleAspectFit;
        _bottomImageView.image = image(@"img_main_bottom");
        [_scrollView addSubview:_bottomImageView];
    }
    return _bottomImageView;
}
- (NSMutableArray *)firstBannerImages {
    if (!_firstBannerImages) {
        //        _firstBannerImages = [[NSMutableArray alloc] initWithObjects:@"http://pic33.photophoto.cn/20141022/0019032438899352_b.jpg",@"http://pic33.photophoto.cn/20141022/0019032438899352_b.jpg",@"http://pic33.photophoto.cn/20141022/0019032438899352_b.jpg", nil];
        _firstBannerImages = [[NSMutableArray alloc] init];
    }
    return _firstBannerImages;
}
- (NSMutableArray *)bannerArray {
    if (!_bannerArray) {
        _bannerArray = [[NSMutableArray alloc] init];
    }
    return _bannerArray;
}
- (NSMutableArray *)liveArray {
    if (!_liveArray) {
        _liveArray = [[NSMutableArray alloc] init];
    }
    return _liveArray;
}


- (NSMutableArray *)activityArray {
    if (!_activityArray) {
        //        _activityArray = [[NSMutableArray alloc] initWithObjects:@"11",@"222", nil];
        _activityArray = [[NSMutableArray alloc] init];
    }
    return _activityArray;
}

@end
